package cuiyt.leetcode.tree;

import cuiyt.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.Objects;
import java.util.Stack;

public class T145二叉树的后序遍历 {
    public static void main(String[] args) {

    }

    public static void printTreeByTail(TreeNode node, ArrayList<Integer> list){
        if(Objects.isNull(node)){
            return;
        }
        printTreeByTail(node.left,list);
        printTreeByTail(node.right,list);
        int val = node.val;
        list.add(val);
    }

    public static void printTreeByTailV2(TreeNode head, ArrayList<Integer> list){
        if(Objects.isNull(head)){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        // 加入根节点
        stack.push(head);
        while (!stack.isEmpty()){
            // 拿到当前的节点进行后序遍历，左 右 中
            TreeNode node = stack.pop();
            stack2.push(node);
            if(node.left != null){
                stack.push(node.left);
            }
            if(node.right != null){
                stack.push(node.right);
            }
        }
        while (!stack2.isEmpty()){
            list.add(stack2.pop().val);
        }
    }

    public static void postOrderIteration(TreeNode head) {
        if (head == null) {
            return;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        stack1.push(head);
        while (!stack1.isEmpty()) {
            TreeNode node = stack1.pop();
            // 入栈
            stack2.push(node);
            // 右子树
            if (node.left != null) {
                stack1.push(node.left);
            }
            // 左子树
            if (node.right != null) {
                stack1.push(node.right);
            }
        }
        while (!stack2.isEmpty()) {
            System.out.print(stack2.pop().val + " ");
        }
    }

}
